import {isJSON} from './isJSON.js'

class WebSocketClass {
  constructor(url) {
    this.lockReconnect = false;  // 是否开始重连
    this.wsUrl = "";  // ws 地址
    this.globalCallback = null;  // 回调方法
    this.userClose = false;  // 是否主动关闭
    this.createWebSocket(url);
	this.pingInterval = null;
  }

  createWebSocket(url) {
    // #ifdef H5
    if (typeof (WebSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket，无法获取数据");
      return false
    }
    // #endif

    // #ifdef APP-PLUS
    if (typeof (uni.connectSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket，无法获取数据");
      return false
    }
    // #endif

    this.wsUrl = url;
    try {
      // 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】

      // #ifdef H5
      this.ws = new WebSocket(this.wsUrl);
      this.initEventHandle();
      // #endif

      // #ifdef APP-PLUS
      this.ws = uni.connectSocket({
        url: this.wsUrl,
        success(data) {
          
          this.initEventHandle();
        },
      });
      // #endif
    } catch (e) {
      this.reconnect(url);
    }
  }

  // 初始化
  initEventHandle() {
    /**
     * 监听WebSocket连接打开成功
     */

    // #ifdef H5
    this.ws.onopen = (event) => {
	  this.reconnectDelay = 1000;
	  this.startHeartbeat();
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onOpen(res => {
	  this.reconnectDelay = 1000;
	  this.startHeartbeat();
    });
    // #endif

    
    /**
     * 连接关闭后的回调函数
     */

    // #ifdef H5
    this.ws.onclose = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onClose(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif
    

    /**
     * 报错时的回调函数
     */ 

    // #ifdef H5
    this.ws.onerror = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onError(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif


    /**
     * 收到服务器数据后的回调函数
     */ 
    
    // #ifdef H5
    this.ws.onmessage = (event) => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)
        
        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onMessage(event => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)

        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    });
    // #endif
  }
  
startHeartbeat() {
  this.pingInterval = setInterval(() => {
	this.ws.send("ping");
  }, 30000); // 每10秒发送一次心跳
}

// 停止心跳检测
  stopHeartbeat() {
    if (this.pingInterval) {
      clearInterval(this.pingInterval);
      this.pingInterval = null;
    }
  }
	
	

  // 关闭ws连接回调
	reconnect(url) {
	  if (this.lockReconnect) return;
	  this.ws.close();
	  this.lockReconnect = true;
	  this.reconnectDelay = this.reconnectDelay ? (this.reconnectDelay * 2) : 1000;
	  setTimeout(() => {
		this.createWebSocket(url);
		this.lockReconnect = false;
	  }, this.reconnectDelay);
	}


  // 发送信息方法
  webSocketSendMsg(msg) {
    this.ws && this.ws.send({
      data: msg,
      success() {
      },
      fail(err) {
      }
    });
  }

  // 获取ws返回的数据方法
  getWebSocketMsg(callback) {
    this.globalCallback = callback
  }

  // 关闭ws方法
  closeSocket() {
    if (this.ws) {
		this.stopHeartbeat();
      this.userClose = true;
      this.ws.close({
        success(res) {
        },
        fail(err) {
        }
      });
    }
  }

  writeToScreen(massage) {
  }
}
export default WebSocketClass;


